<?php
declare (strict_types=1);

namespace app\admin\controller\query;

use app\admin\controller\CommonController;
use app\common\model\QueryAmass;
use ffhome\frame\service\DictDataService;

class Amass extends CommonController
{
    protected $modelName = QueryAmass::MODEL_NAME;
    protected $alias = 'a';
    protected $deleteField = 'delete_time';

    protected function buildWhere(array $param): array
    {
        $where = parent::buildWhere($param);
        $controller = request()->controller();
        if (!auth($controller . '/seeAll')) {
            $type = [-1];
            $list = DictDataService::getByParentName('amass_type_list');
            foreach ($list as $item) {
                if (auth($controller . '/seeMarket' . $item['value'])) {
                    $type[] = $item['value'];
                }
            }
            $where[] = ["{$this->alias}.type", 'in', $type];
        }
        return $where;
    }

    protected function setDefaultValueInAddPage(array $row): array
    {
        $row['type'] = request()->param('type');
        $this->assign('title', DictDataService::getNameByValue($row['type'], 'amass_type_list') . lang('amass.title'));
        $row['person_num'] = 1;
        return $row;
    }

    protected function getAddSuccessInfo($data): string
    {
        return lang('amass.addSuccessInfo');
    }

    protected function getExportHeader()
    {
        return [
            [lang('amass.type'), 'type_name']
            , [lang('amass.travel_name'), 'travel_name']
            , [lang('amass.username'), 'username']
            , [lang('amass.mobile'), 'mobile']
            , [lang('amass.position'), 'position']
            , [lang('amass.person_num'), 'person_num']
        ];
    }

    protected function convertExportData(&$list)
    {
        foreach ($list as &$item) {
            $item['type_name'] = DictDataService::getNameByValue($item['type'], 'amass_type_list');
        }
    }

    public function statByType()
    {
        $param = request()->param();
        $where = $this->buildWhere($param);
        $this->assign('param', $param);
        $list = $this->getSearchModel($where)
            ->field("{$this->alias}.type,count({$this->alias}.id) travel_count,sum({$this->alias}.person_num) person_num")
            ->group("{$this->alias}.type")->select()->toArray();
        $this->assign('list', $list);
        return $this->fetch();
    }
}
